{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "05069f3e-3e53-4b21-a819-31d59a7157d3",
   "metadata": {},
   "source": [
    "Chapter 08\n",
    "# 利用global在函数内部声明全局变量\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "49589c4e-cc7b-4a49-8fda-d08c87f6f071",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "global_x: 8\n"
     ]
    }
   ],
   "source": [
    "# 全局变量\n",
    "global_x = 8 # global_x: 8\n",
    "print(\"global_x:\", global_x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "192c11cc-9807-47d7-b2c9-d6c13aabbac9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自定义函数\n",
    "def my_function(local_x):\n",
    "    # 局部变量\n",
    "    print(\"local_x:\", local_x) # local_x: 38\n",
    "    \n",
    "    # 声明变量是全局变量\n",
    "    global global_x\n",
    "    global_x = 88 \n",
    "    print(\"global_x:\", global_x) # global_x: 88"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4772cdd5-ee8f-4626-9753-606ac770f84b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "local_x: 38\n",
      "global_x: 88\n"
     ]
    }
   ],
   "source": [
    "# 调用函数\n",
    "my_function(38)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b09b0c25-84a4-4717-bd57-02be60cb3cf5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "global_x: 88\n"
     ]
    }
   ],
   "source": [
    "# 在函数外部访问全局变量\n",
    "print(\"global_x:\", global_x) # global_x: 88"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
